package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.xxx.xbutler.data.RobotMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Robot;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 平台机器人回收回调
 * <p>
 * 平台机器人从商家下回收时，开放平台会主动推送此回调通知对应的商家；
 *
 * <pre>
 * {
 *     "nType": 1047,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "RobotList": [
 *             "691BEC414C932D3D114F80CCBB25881E"
 *         ]
 *     },
 *     "nTimeStamp": 1603798901202
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1047Handler implements CallbackHandler {

    @Resource
    private RobotMapper robotMapper;

    @Override
    public String name() {
        return "平台机器人回收回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 1047;
    }

    @Override
    public void handle(Callback callback) {
        JSONObject data = (JSONObject) callback.getData();
        JSONArray robots = data.getJSONArray("RobotList");
        List<String> robotSerialNos = robots.stream()
                .map(Object::toString)
                .toList();
        LambdaUpdateWrapper<Robot> wrapper = new LambdaUpdateWrapper<Robot>()
                .in(Robot::getSerialNo, robotSerialNos);
        robotMapper.delete(wrapper);
    }
}
